package com.ruoyi.edit.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.common.utils.DateUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.edit.domain.*;
import com.ruoyi.edit.domain.VO.VendorCourseVO;
import com.ruoyi.edit.service.*;
import com.ruoyi.edit.utils.AssertUtil;
import com.ruoyi.edit.utils.CopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.NumberUtils;

/**
 * 课程Controller
 *
 * @author ruoyi
 * @date 2022-03-07
 */
@Controller
@RequestMapping("/system/course")
public class VendorCourseController extends BaseController {
    private String prefix = "system/course";

    @Autowired
    private IVendorCourseService vendorCourseService;

    @Autowired
    private ICourseContentService courseContentService;

    @Autowired
    private ICoursePackageV2Service coursePackageV2Service;

    @Autowired
    private IVendorCourseRelPackagev2Service courseRelPackagev2Service;

    @Autowired
    private OssService ossService;

    @Value("${oss.path}")
    public  String path;

    @Value("${oss.url}")
    public  String ossUrl;

    @GetMapping()
    public String course(String id, ModelMap mmap) {
        mmap.put("id", id);
        return prefix + "/course";
    }

    /**
     * 查询课程列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(VendorCourse vendorCourse) {
        startPage();
        List<VendorCourse> list = vendorCourseService.selectVendorCourseList(vendorCourse);
        return getDataTable(list);
    }

    /**
     * 导出课程列表
     */
    @Log(title = "课程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(VendorCourse vendorCourse) {
        List<VendorCourse> list = vendorCourseService.selectVendorCourseList(vendorCourse);
        ExcelUtil<VendorCourse> util = new ExcelUtil<VendorCourse>(VendorCourse.class);
        return util.exportExcel(list, "课程数据");
    }

    /**
     * 新增课程
     */
    @GetMapping("/add")
    public String add(String coursePackageId, ModelMap mmap) {
        mmap.put("coursePackageId", coursePackageId);
        return prefix + "/add";
    }

    /**
     * 新增保存课程
     */
    @Log(title = "课程", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(VendorCourse vendorCourse) {
        vendorCourseService.insertVendorCourse(vendorCourse);
        return toAjax(1);
    }

    /**
     * 修改课程
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        VendorCourse vendorCourse = vendorCourseService.selectVendorCourseById(id);
        VendorCourseVO vo = getVendorCourseVO(vendorCourse);
        mmap.put("vendorCourse", vo);
        return prefix + "/edit";
    }

    /**
     * 修改保存课程
     */
    @Log(title = "课程", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(VendorCourse vendorCourse) {
        return toAjax(vendorCourseService.updateVendorCourse(vendorCourse));
    }

    /**
     * 删除课程
     */
    @Log(title = "课程", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(vendorCourseService.deleteVendorCourseByIds(ids));
    }


    /**
     * 导入课程
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file) {
        try {
            vendorCourseService.importTemplate(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(1);
    }


    /**
     * 上传图片
     */
    @PostMapping("/importImg")
    @ResponseBody
    public AjaxResult importImg(MultipartFile file, String id) {
        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        String fileName = "admin" + "_" + System.currentTimeMillis() + extension;
        String url = ossService.aliyunOssUpload(path + "common/" + fileName, file);
        VendorCourse vendorCourse = vendorCourseService.selectVendorCourseById(id);
        if (AssertUtil.isEmpty(vendorCourse)) {
            return AjaxResult.error("id不存在");
        }
        vendorCourse.setCover(ossUrl + url);
        vendorCourseService.updateVendorCourse(vendorCourse);
        return toAjax(1);
    }

    public static VendorCourseVO getVendorCourseVO(VendorCourse vendorCourse) {
        VendorCourseVO vo = new VendorCourseVO();
        CopyUtils.copyProperties(vendorCourse, vo);

        if (AssertUtil.isNotEmpty(vendorCourse.getDetails())) {
            boolean q0 = false;
            boolean q1 = false;
            boolean q2 = false;
            List<Object> list = JSON.parseArray(vendorCourse.getDetails());
            for (int i = 0; i < list.size(); i++) {
                Map map = transJsonToMap(String.valueOf(list.get(i)));

                if (StringUtils.equals(String.valueOf(map.get("label")), "周次")) {
                    vo.setType_1_1_val(String.valueOf(map.get("value")));
                    q2 = true;
                }
                if (StringUtils.equals(String.valueOf(map.get("label")), "教材")) {
                    vo.setType_1_2_val(String.valueOf(map.get("value")));
                }
                if (StringUtils.equals(String.valueOf(map.get("label")), "面向")) {
                    vo.setType_2_1_val(String.valueOf(map.get("value")));
                    q0 = true;
                }
                if (StringUtils.equals(String.valueOf(map.get("label")), "课堂时间")) {
                    vo.setDurations(String.valueOf(map.get("value")));
                }
                if (StringUtils.equals(String.valueOf(map.get("label")), "课程编号")) {
                    vo.setIndexInPackage(Long.valueOf(String.valueOf(map.get("value"))));
                    q1 = true;
                }
                if (StringUtils.equals(String.valueOf(map.get("label")), "月龄")) {
                    vo.setDimensions(String.valueOf(map.get("value")));
                }
            }
            if (q2) {
                vo.setTypeName(2);
                if (q0) {
                    vo.setTypeName(0);
                }
            }
            if (q1) {
                vo.setTypeName(1);
            }
        }

        return vo;
    }

    public static Map<String, String> transJsonToMap(String source) {
        Map<String, String> map = JSON.parseObject(source, Map.class);
        return map;
    }


    /**
     * 将字符串日期格式化为日期对象。
     *
     * @param formatDate 字符串日期
     * @return 日期对象
     * @throws ParseException
     */
    public static final Date parseToDateMilis(String formatDate) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (formatDate.contains("年") || formatDate.contains("月") || formatDate.contains("日")) {
                sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
                Date dt = sdf.parse(formatDate);
                return dt;
            }
            if (formatDate.contains("/")) {
                sdf = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
                Date dt = sdf.parse(formatDate);
                return dt;
            }
            Date dt = sdf.parse(formatDate);
            return dt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Date();
    }

    /**
     * 公共课程拷贝到课程教保指引
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/copyCoursePackagesV2")
    public String copyCoursePackagesHtml(String id, ModelMap mmap) {
        mmap.put("id", id);
        return prefix + "/copyCoursePackagesV2";
    }

    /**
     * 拷贝到课程  改为了关联到
     */
    @PostMapping("/copyCourseContentV2")
    @ResponseBody
    public AjaxResult copyCourseContentV2(String[] id, String coursePackageV2Id) {
        VendorCourseRelPackagev2 vendorCourseRelPackagev2 = null;
        for (int i = 0; i < id.length; i++) {
//            courseContentService.copyPackagesV2(id[i],coursePackageV2Id);
            vendorCourseRelPackagev2 = new VendorCourseRelPackagev2();
            vendorCourseRelPackagev2.setVendorCourseId(id[i]);
            vendorCourseRelPackagev2.setPackageV2Id(coursePackageV2Id);
            List<VendorCourseRelPackagev2> list = courseRelPackagev2Service.selectVendorCourseRelPackagev2List(vendorCourseRelPackagev2);
            if (list.size() == 0) {
                courseRelPackagev2Service.insertVendorCourseRelPackagev2(vendorCourseRelPackagev2);
            }
        }
        return toAjax(1);
    }

    /**
     * 拷贝到课程  改为了关联到
     */
    @PostMapping("/copyCourseContentV2_1")
    @ResponseBody
    public AjaxResult copyCourseContentV2_1(String[] id, String coursePackageV2Id) {
        VendorCourseRelPackagev2 vendorCourseRelPackagev2 = null;
        for (int i = 0; i < id.length; i++) {
//            courseContentService.copyPackagesV2(id[i],coursePackageV2Id);
            vendorCourseRelPackagev2 = new VendorCourseRelPackagev2();
            vendorCourseRelPackagev2.setVendorCourseId(id[i]);
            vendorCourseRelPackagev2.setPackageV2Id(coursePackageV2Id);
            List<VendorCourseRelPackagev2> list = courseRelPackagev2Service.selectVendorCourseRelPackagev2List(vendorCourseRelPackagev2);
            if (list.size() == 0) {
                courseRelPackagev2Service.insertVendorCourseRelPackagev2(vendorCourseRelPackagev2);
            }
        }
        return toAjax(1);
    }

    /**
     * 拷贝课程结构所有
     */
    @PostMapping("/copyStructure")
    @ResponseBody
    public AjaxResult copyStructure(String id) {
        courseContentService.copyStructure(id);
        return toAjax(1);
    }
}
